/**WebSocket插件
 *
 * @CreateBy：zhangsen@protonmail.com
 * @CreateOn：2018-08-10
 * @param jason
 * @returns {{init: init}}
 * @constructor
 */

var JWebSocket = function (options) {
    var default_options = {
        uri: "#", // Socket绑定的URI
        sockJsUri: "#",
        projectName: window.location.pathname.split("/")[1], // 项目名称。默认以“/”为分隔符切割URI后取第2个字符串
        host: window.location.host, // 项目IP和端口。默认取当前项目的主机IP和Port
        open: function (event) {
            // 自定义WSC连接事件：服务端与前端连接成功后触发
             console.log("开始通信，建立连接成功")
        },
        message: function (event) {
            // 自定义WSC消息接收事件：服务端向前端发送消息时触发
            /*console.log(event)*/
        },
        error: function (event) {
            // 自定义WSC异常事件：WSC报错后触发
            console.log("连接出现异常")
        },
        close: function (event) {
            // 自定义WSC关闭事件：WSC关闭后触发
            console.log("通信完毕，关闭连接成功")
        }
    };
    this.$websocket = null;

    this.$options = $.extend({},  default_options, options)
    /*this.open_connet();*/
    return this;
}
JWebSocket.prototype = {
    open_connet: function () {
        var websocket;
        if ('WebSocket' in window) {
            websocket = new WebSocket("ws://" + this.$options.host + "/" + this.$options.projectName + "/" + this.$options.uri);
        } else if ('MozWebSocket' in window) {
            websocket = new MozWebSocket("ws://" + this.$options.host + "/" + this.$options.projectName + "/" + this.$options.uri);
        } else {
            websocket = new SockJS("http://" + this.$options.host + "/" + this.$options.projectName + "/" + this.$options.sockJsUri);
        }
        this.$websocket = websocket;
       var _option= this.$options;
        this.$websocket.onopen = function (evnt) {
            _option.open(evnt);
        };
        this.$websocket.onmessage = function (evnt) {
            _option.message(evnt);
        };
        this.$websocket.onerror = function (evnt) {
            _option.error(evnt);
        };
        this.$websocket.onclose = function (evnt) {
            _option.close(evnt);
        };
        return this;
    },
    close: function () {
        if(this.$websocket){
            this.$websocket.close();
        }
        return this;
    } ,
    send:function (msg) {
        this.$websocket.send(msg);
        return this;
    }

}

